import {Component} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {AppUrl} from "../../../../app/app.general";
import {HttpClient} from "@angular/common/http";
import {FileUploader} from "ng2-file-upload";

/**
 * Generated class for the FoodMenuAddPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-food-menu-add',
  templateUrl: 'food-menu-add.html',
})
export class FoodMenuAddPage {

  pageMenu = {
    tittle: '菜品添加',
    name: '*名称：',
    price: '*价格（元）：',
    type: '*分类：',
    stock: '数量：',
    remark: '菜品说明'
  };

  name: any;
  price: any;
  stock: any = 100;
  foodtype: any;
  foodId: any;
  remark: any = '';
  private uploadStatus: boolean = false;

  foodTypeList = [
    // {id:1,foodtype:'凉菜'},
    // {id:2,foodtype:'炒菜'},
    // {id:3,foodtype:'特色'},
    // {id:4,foodtype:'汤'},
  ];

  opType: any;
  private imgId: any = '';

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: HttpClient, private alerCtrl: AlertController) {
    this.opType = this.navParams.get("opType");
    if (this.opType == 'modify') {
      this.pageMenu.tittle = '菜品修改';
      this.foodId = this.navParams.get("id");
      this.name = this.navParams.get("foodname");
      this.price = this.navParams.get("price");
      this.stock = this.navParams.get("stock");
      this.foodtype = this.navParams.get("foodtype");
      this.imgId = this.navParams.get("imgId");
      this.remark = this.navParams.get("remark");
    }
    //获取菜品分类
    this.http.post(AppUrl.foodType.selectByRestID, {restId: localStorage.getItem('restaurantid')}).subscribe(data => {
      let temp: any = data;
      this.foodTypeList = temp.data;

    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FoodMenuAddPage');
  }

  showAlert(message) {
    let alert = this.alerCtrl.create({
      title: '警告',
      subTitle: message,
      buttons: ['确定']
    });
    alert.present();
  }

  private upload = false;

  output(e) {
    this.imgId = e;
    if (this.opType == 'add') {//TODO:'imgId'根据实际情况
      this.imgId = e;
      this.http.post(AppUrl.food.insert, {
        foodname: this.name.trim(), foodtype: this.foodtype, price: this.price,
        belong: localStorage.getItem('restaurantid'), sale: '', del: 0,
        stock: this.stock, imgId: this.imgId, remark: this.remark
      }).subscribe(data => {
        this.navCtrl.pop();
      });
    }
    else if (this.opType == 'modify') {
      console.log("foodID:" + this.foodId);

      this.http.post(AppUrl.food.updateFood, {
        id: this.foodId, foodname: this.name.trim(), foodtype: this.foodtype, price: this.price,
        stock: this.stock, imgId: this.imgId, remark: this.remark
      }).subscribe(data => {
        this.navCtrl.pop();

      });
    }

  }


  submit() {
    if (this.name == null || this.price == null || this.foodtype == null) {
      this.showAlert("带*号为必填项");
      return;
    }
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (this.name.trim() == '') {
      this.showAlert("带*号为必填项");
      return;
    }
    if (!reg.test(this.price)) {
      this.showAlert("请输入正确的价格");
      return;
    }
    if (this.stock != null) {
      var regT = /^\+?[1-9]\d*$/;
      if (!regT.test(this.stock)) {
        this.showAlert("请输入正确的库存数量");
        return;
      }
    }
    this.upload = true;
    // if (!this.imgId || this.imgId.trim() != '') {
    //   this.showAlert("请上传一张菜品图片");
    //   return;
    // }


  }

  selectedFileOnChanged(index: number) {
    let $this = this;
    let selectedArr = this.selectedImgUrl;
    this.uploader.queue.forEach((q, i) => {
      let reader = new FileReader();
      let qq: any = q;
      reader.readAsDataURL(qq.some);
      reader.onload = function () {
        let imgs = {
          url: this.result,
          uploadID: i,
          pIndex: index
        };
        if (selectedArr.length > 0) {
          let isSame = false;
          selectedArr.forEach((img, j) => {
            if (img.url == this.result) {
              isSame = true;
            }
          });
          if (!isSame) {
            selectedArr.push(imgs);
          } else {
            $this.uploader.queue[i].remove();
            $this.selectedImgLength = $this.uploader.queue.length;
          }
        } else {
          selectedArr.push(imgs)
        }
      }
    });
    this.selectedImgLength = this.uploader.queue.length;
  }

  public uploader: FileUploader = new FileUploader({url: ''});
  selectedImgUrl: any[] = [];
  selectedImgLength = 0;


  uploadImg() {
    let $this = this;
    this.selectedImgUrl.forEach((img, i) => {
      this.uploader.queue[i]['pIndex'] = img.pIndex;
    });
    this.uploader.uploadAll();
    this.uploader.onSuccessItem = (item, res, status, headers) => {
      if (status == 200) {
        let tempRes = JSON.parse(res);
      } else {

      }
    };
    this.uploader.onCompleteAll = function () {

    }
  }

  removeUpload(img) {
    this.uploader.queue[img.uploadID].remove();
    this.selectedImgUrl.splice(img.uploadID, 1);
    this.selectedImgUrl.forEach((up, i) => {
      up.uploadID = i;
    });
    this.selectedImgLength = this.uploader.queue.length;
    console.log(this.uploader);
  }

}
